package com.yuan.support;

import android.Manifest;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Fragment;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Build;
import android.os.storage.StorageManager;
import android.os.storage.StorageVolume;
import android.preference.PreferenceManager;
import android.util.Log;
import android.widget.ImageView;

import java.io.File;

import static android.app.Activity.RESULT_OK;

/**
 * SD卡写权限申请框、保存授权Uri等
 * <p>
 * SDCardFragment 独用的方法才放在 SDCardFragment 里
 */
public class SDCardFragment extends Fragment {
    private static final String TAG = SDCardFragment.class.getSimpleName();

    public static final int SD_CARD_PERMISSION = 5000;

    public static final int REQUEST_CODE_PERMISSION = 1000; // 内置SD卡写权限

    public static final int REQUEST_PERMISSION_INTERVAL = 10 * 1000; // 请求权限的间隔时间
    public static long lastRequestTime = 0; // 上次的请求时间

    @Override
    public void onResume() {
        super.onResume();
        Log.d(TAG, "onResume: " + Log.getStackTraceString(new Throwable()));

        //
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            Activity activity = getActivity();
            if (activity.checkSelfPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
                // todo 不判断而直接申请的话，已授权情况下，虽不会弹框，但会不停调用 onResume ？ 不是主因，主因在未 remove Fragment
                Log.d(TAG, "onResume: requestPermissions");
                activity.requestPermissions(new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, REQUEST_CODE_PERMISSION);
            }
        }

        // region 避免重复弹框
        long currentTimeMillis = System.currentTimeMillis();
        long diff = currentTimeMillis - lastRequestTime;
        if (diff < REQUEST_PERMISSION_INTERVAL) {
            Log.d(TAG, "checkSDCardPermission: diff=" + diff);
            // 小于请求间隔时，不应弹框，故直接返回
            return;
        } else {
            // 大于请求间隔时，记录本次时间，继续其它判断操作
            lastRequestTime = currentTimeMillis;
        }
        // endregion
        requestSDCardWritePermission();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        Log.d(TAG, "onDestroy: ");
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (resultCode == RESULT_OK) {
            if (requestCode == SD_CARD_PERMISSION) {
                Uri treeUri = data.getData();
                saveTreeUri(treeUri);
            }
        }
    }

    /**
     * 申请外置SD卡写权限
     */
    private void requestSDCardWritePermission() {
        Activity activity = getActivity();

        StorageManager storageManager = (StorageManager) activity.getSystemService(Context.STORAGE_SERVICE);

        Log.d(TAG, "requestSDCardWritePermission: SDK_INT=" + Build.VERSION.SDK_INT);

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            StorageVolume volume = storageManager.getStorageVolume(new File(DocumentFileUtils.getSDRootPath()));
            Intent intent = volume.createAccessIntent(null);
            Log.d(TAG, "requestSDCardWritePermission: intent=" + intent);
            startActivityForResult(intent, SD_CARD_PERMISSION); // 最好放在Fragment里
        } else {
            ImageView imageView = new ImageView(getActivity().getApplicationContext());
            imageView.setBackground(getResources().getDrawable(R.drawable.sdcardpermissionstep));

            AlertDialog alertDialog = new AlertDialog.Builder(getActivity())
                    .setView(imageView)
                    .setTitle("开启SD卡权限步骤")
                    .setPositiveButton("前往设置", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            Intent intent = new Intent(Intent.ACTION_OPEN_DOCUMENT_TREE);
                            Log.d(TAG, "requestSDCardWritePermission: intent=" + intent);
                            startActivityForResult(intent, SD_CARD_PERMISSION); // 最好放在Fragment里
                        }
                    })
                    .create();
            alertDialog.show();
        }
    }

    /**
     * 授权后保存外置SD卡写权限的Uri
     */
    private void saveTreeUri(Uri uri) {
        Log.d(TAG, "saveTreeUri: " + uri + "\n" + uri.toString());

        Context context = getActivity().getApplicationContext();

        String sdRootPath = DocumentFileUtils.getSDRootPath();

        // com.cib.dgqb_preferences.xml
        PreferenceManager.getDefaultSharedPreferences(context)
                .edit()
                .putString(sdRootPath, uri.toString())
                .apply();

        // todo 拔后再插权限还在
        // 为了下次不用反复请求权限的问题，保存授权在系统了，即使reboot了也依然存在，除非clear APP data.
        context.getContentResolver().takePersistableUriPermission(uri,
                Intent.FLAG_GRANT_WRITE_URI_PERMISSION | Intent.FLAG_GRANT_READ_URI_PERMISSION);

        // todo 不移除的后果，授予权限后，Activity的onResume时会调用Activity相关联的Fragment的onResume
        getActivity().getFragmentManager().beginTransaction()
                .remove(this)
                .commitAllowingStateLoss();
    }

}
